/**
* 系统管理 患者管理
*/
<template>
  <div style="width: 100%;height: 100%">
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入患者姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchByNameOrPhone">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="handleAdd">
          <font-awesome-icon icon="fas fa-plus" />
          <span style="margin-left:1vh">患者录入</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>
    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[5, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table
        :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }"
        size="large"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;height: 50%"
        :data="userList"
        v-loading="loading"
        highlight-current-row
        class="customer-table"
        border
        element-loading-text="拼命加载中">
      <!--      <el-table-column align="center" type="selection" width="50">-->
      <!--      </el-table-column>-->
      <el-table-column  sortable prop="userId" label="患者编号" width="150">
      </el-table-column>
      <el-table-column  sortable prop="name" label="患者姓名" width="150">
      </el-table-column>
      <el-table-column  sortable prop="username" label="手机号" width="150">
      </el-table-column>
      <el-table-column  sortable prop="sex" label="性别" min-width="100">
      </el-table-column>
      <el-table-column  sortable prop="age" label="年龄" min-width="100">
      </el-table-column>
      <el-table-column  sortable prop="height" label="身高" min-width="100">
      </el-table-column>
      <el-table-column  sortable prop="weight" label="体重" min-width="100">
      </el-table-column>
      <!--      <el-table-column  sortable prop="serialCode" label="绑定设备序列号" min-width="200">-->
      <!--      </el-table-column>-->
      <!--      <el-table-column  sortable prop="status" label="设备状态" min-width="150">-->
      <!--      </el-table-column>-->
      <!--      <el-table-column  sortable prop="productionTime" label="设备生产时间" min-width="150">-->
      <!--        <template v-slot="scope">-->
      <!--          {{ dateUtils.formatDateTime(scope.row.productionTime) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column  sortable prop="activationTime" label="设备激活时间" min-width="150">-->
      <!--        <template v-slot="scope">-->
      <!--          {{ dateUtils.formatDateTime(scope.row.expirationTime) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column  sortable prop="expirationTime" label="设备截止时间" min-width="150">-->
      <!--        <template v-slot="scope">-->
      <!--          {{ dateUtils.formatDateTime(scope.row.expirationTime) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column fixed="right" label="操作" min-width="300">
        <template v-slot="scope">
          <el-button size="default" type="success" @click="handleEdit(scope.row)">
            <font-awesome-icon icon="fas fa-edit" />
            <span style="">编辑信息</span>
          </el-button>
          <!-- <el-button size="small" type="success" @click="resetpwd(scope.$index, scope.row)">重置密码</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="患者信息编辑" v-model="editFormVisible" width="30%" align-center center @close="editFormClose">
      <el-form style="display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;flex-wrap: wrap">
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">姓名:</el-text>
          <el-input style="width: 80%" v-model="editForm.name"  autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">手机号:</el-text>
          <el-input style="width: 80%" v-model="editForm.username" placeholder="请输入患者手机号" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">性别:</el-text>
          <el-select style="width: 80%" v-model="editForm.sex" placeholder="请选择患者性别" autocomplete="off">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item  style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <div class="demo-date-picker">
            <el-text size="large" style="width: 20%">出生日期:</el-text>
            <div class="block">
              <el-date-picker
                  autocomplete="off"
                  v-model="editForm.birthTime"
                  type="date"
                  :disabled-date="disabledDate"
                  placeholder="请输入患者出生日期"
              />
            </div>
          </div>

        </el-form-item >
        <!--        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">-->
        <!--          <el-text size="large" style="width: 20%">年龄:</el-text>-->
        <!--          <el-input style="width: 80%" v-model="editForm.age" placeholder="请输入患者年龄" autocomplete="off"/>-->
        <!--        </el-form-item>-->

        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">身高:</el-text>
          <el-input style="width: 80%" v-model="editForm.height" placeholder="请输入患者身高" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">体重:</el-text>
          <el-input style="width: 80%" v-model="editForm.weight" placeholder="请输入患者体重" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmEdit">保存</el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog title="患者录入" v-model="addFormVisible" width="30%" align-center center @close="addFormClose">
      <el-form style="display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;flex-wrap: wrap">
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">姓名:</el-text>
          <el-input style="width: 80%" v-model="addForm.name" placeholder="请输入患者姓名" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">手机号:</el-text>
          <el-input style="width: 80%" v-model="addForm.username" placeholder="请输入患者手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">身高（cm）:</el-text>
          <el-input style="width: 80%" v-model="addForm.height" placeholder="请输入患者身高" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">体重（kg）:</el-text>
          <el-input style="width: 80%" v-model="addForm.weight" placeholder="请输入患者体重" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">性别:</el-text>
          <el-select style="width: 80%" v-model="addForm.sex" placeholder="请选择患者性别" autocomplete="off">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
          <!--          <el-input style="width: 80%" v-model="addForm.sex" placeholder="请输入患者性别" autocomplete="off"/>-->
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">出生日期:</el-text>
          <div class="block">
            <el-date-picker
                autocomplete="off"
                v-model="addForm.birthTime"
                type="date"
                :disabled-date="disabledDate"
                placeholder="请输入患者出生日期"
                value-format="YYYY-MM-DD"
            />
          </div>

        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmAdd">保存</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import Pagination from '../../components/Pagination.vue';
import {onMounted, ref} from "vue";
import doctor from "@/api/doctor.js";
import admin from "@/api/admin.js";
import {ElMessage} from "element-plus";
import * as dateUtils from "@/utils/dateUtils.js";
import FilterList from "@/components/tableViews/filterList.vue";
const loading = ref(false);
const title = ref('添加用户');
const editFormVisible = ref(false);
const editForm = ref({
  name:'',
  username: '',
  birthTime:'',
  sex: '',
  age: '',
  height: '',
  weight: '',
});
const userList = ref([]);

const value1 = ref('');
const disabledDate = (time) => {
  return time.getTime() > Date.now()
};
//按钮查询过滤
const rows = ref([
  { label: '设备状态', buttons: [
      { text: '-全部-', value: null, selected: true },
      { text: '申请绑定', value: 0, selected: false },
      { text: '已绑定', value: 1, selected: false },
      { text: '拒绝绑定', value: 2, selected: false },
    ] },
  { label: '性别', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '男',value:'男', selected: false },
      { text: '女',value:'女', selected: false },
    ] },
  { label: '年龄', buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '0到10岁',value:0, selected: false },
      { text: '11到20岁',value:10, selected: false },
      { text: '21到30岁',value:20, selected: false },
      { text: '31到40岁',value:30, selected: false },
      { text: '51到50岁',value:40, selected: false },
      { text: '51到60岁',value:50, selected: false },
      { text: '60岁以上',value:200, selected: false },
    ] },
]);
const updateList = (rows) =>{
  const userSearchQuery = {
    name:formInline.value.userName,
    username:formInline.value.userName,
    status:null,
    sex:null,
    age:null,
    ageEnd:null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }


  // 调用更新方法
  updateUserSearchQuery(rows, userSearchQuery);
  requestUserList(userSearchQuery);
}

//分页模块
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const userSearchQuery = {
    name:null,
    username:null,
    status:null,
    sex:null,
    age:null,
    ageEnd:null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  // 调用更新方法
  updateUserSearchQuery(rows.value, userSearchQuery);
  //执行查询
  requestUserList(userSearchQuery);
}
const handleSizeChange = ()=>{
  const deviceListQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateUserSearchQuery(rows.value,deviceListQuery)
  requestUserList(deviceListQuery)
}
function updatePageParams(pageData) {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}

//列表查询
onMounted(() => {
  getUserList();
});
const updateUserSearchQuery = (rows, userSearchQuery)=>{
  userSearchQuery.status = updateSelectedValue(rows[0].buttons);
  userSearchQuery.sex = updateSelectedValue(rows[1].buttons);
  userSearchQuery.age = updateSelectedValue(rows[2].buttons);
  userSearchQuery.ageEnd = updateSelectedValue(rows[2].buttons) + 10;
}
const requestUserList = (userSearchQuery)=>{
  loading.value = true;
  admin.patientSearch(userSearchQuery)
      .then((res) => {
        if (res.data.code === 200) {
          // 将状态码转换为中文描述
          // 将状态码转换为中文描述
          userList.value = res.data.data.result.map(user => ({
            ...user,
            status: getStatusText(user.status)
          }));
        }
        console.log('res2222',res)
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false;
      })
  ;
}
const getUserList = ()=>{
  const userSearchQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  requestUserList(userSearchQuery)
}
const getStatusText = (statusCode) => {
  switch (statusCode) {
    case 0:
      return "申请绑定";
    case 1:
      return "已绑定";
    case 2:
      return "拒绝绑定";
    default:
      return "未绑定";
  }
};

//编辑弹窗
const formInline = ref({
  userName: '',
  userMobile: '',
});
const handleEdit = (info)=>{
  editForm.value.name = info.name
  editForm.value.username = info.username
  editForm.value.sex = info.sex
  editForm.value.age = info.age
  editForm.value.height = info.height
  editForm.value.weight = info.weight
  editFormVisible.value = true
}
const cancelEdit = ()=>{
  editFormVisible.value = false
}
//根据时间戳计算年龄
function calculateAge(birthTimestamp) {
  // 创建表示当前日期和出生日期的 Date 对象
  const now = new Date();
  const birthDate = new Date(birthTimestamp);

  // 计算年份差异
  let age = now.getFullYear() - birthDate.getFullYear();

  // 获取当前月份和日期
  const month = now.getMonth() - birthDate.getMonth();
  const day = now.getDate() - birthDate.getDate();

  // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减 1
  if (month < 0 || (month === 0 && day < 0)) {
    age--;
  }

  return age;
}

const confirmEdit = ()=>{
  const userInfoEditQuery = editForm.value
  //把时间字符串转为时间戳
  userInfoEditQuery.birthTime=new Date(userInfoEditQuery.birthTime).getTime()
  //把时间戳转为年龄
  userInfoEditQuery.age=calculateAge(userInfoEditQuery.birthTime)
  admin.userInfoEdit(userInfoEditQuery).then((res)=>{
    if (res.data.code === 200){
      ElMessage.success(res.data.msg)
      editFormVisible.value = false
    }else{
      ElMessage.error(res.data.msg)
    }
    getUserList();
  }).catch((err)=>{
    console.log(err)
  })
}
const editFormClose = ()=>{
  editForm.value.name = '';
  editForm.value.username = '';
  editForm.value.sex = '';
  editForm.value.age = '';
  editForm.value.height = '';
  editForm.value.weight = '';
}
//信息查询
const searchByNameOrPhone = ()=>{
  let userSearchQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    userSearchQuery.username = formInline.value.userName
  }else{
    userSearchQuery.name = formInline.value.userName
  }
  requestUserList(userSearchQuery)
}

//新增弹窗
const addFormVisible = ref(false);
const addForm = ref({
  name:'',
  username: '',
});
const handleAdd = ()=>{
  addFormVisible.value = true;
}
const addFormClose = ()=>{
  addForm.value.name = '';
  addForm.value.username = '';
}
const confirmAdd = ()=>{
// 手机号校验
  const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则表达式
  if (!phoneRegex.test(addForm.value.username)) {
    ElMessage.error('请输入有效的手机号');
    return;
  }

  // 将出生日期字符串转换为时间戳
  if (addForm.value.birthTime) {
    const date = new Date(addForm.value.birthTime); // 将日期字符串转换为 Date 对象
    addForm.value.birthTime = date.getTime(); // 获取时间戳
  }

  admin.addUser(addForm.value).then((res)=>{
    if (res.data.code){
      ElMessage.success(res.data.msg);
    }else{
      ElMessage.error(res.data.msg);
    }
    getUserList();
  }).catch((err)=>{
    console.log(err);
  }).finally(()=>{
    addFormVisible.value = false;
  })
}
const cancelAdd = ()=>{
  addFormVisible.value = false;
}
</script>
<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
::v-deep .customer-table th{
  border:none;
}
::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  /* background-color:#04c1a5; */
  background-color: green;
  color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #04c1a5;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
</style>